/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BASearchResultCell.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 8/9/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BASearchResultCell.h"
#import <QuartzCore/QuartzCore.h>
#import "UIImage+MultiplyColor.h"
#import "BAUtils.h"
#import "BALightFrameButton.h"
#import "BALibrarySettings.h"
#import "BAAddReservationViewController.h"
#import "LazyLoadManager.h"
#import "BACoverUrlAndAvailabilityMemoryCache.h"
#ifdef BA_IMF_BUILD
#import "IMFPackageEditManager.h"
#endif
#import "BAPatronSettings.h"

@interface BASearchResultCell (){
    //BOOL shouldRelayout;
}


@property (weak, nonatomic) IBOutlet UIView* myBackgroundView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *authorLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UIButton *seriesButton;
@property (weak, nonatomic) IBOutlet UIButton *addButton;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet BALightFrameButton *reserveButton;

@property (weak, nonatomic) IBOutlet UIView *moreView;
@property (weak, nonatomic) IBOutlet UIImageView *moreImage;
@property (weak, nonatomic) IBOutlet UIImageView *arrowImageView;
@property (weak, nonatomic) IBOutlet UIView *roundDotView;
@property (weak, nonatomic) IBOutlet UILabel *shelfMarkNumber;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLableLeadingSpace;

@end

@implementation BASearchResultCell

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (IBAction)seriesButtonClicked:(id)sender {
    [self.searchResultDelegate searchResultCell:self seriesButtonClickedWithRecord:self.record];
}

- (IBAction)addToPackageButtonClicked:(id)sender {
    if([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        //IMF editing handler
#ifdef BA_IMF_BUILD
        [[IMFPackageEditManager instance] attemptAddRemoveToPackage:self.record
                                                        didAddBlock:^(void) {
                                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                                [self.addButton setSelected:YES];
                                                            });
                                                            
                                                        }
                                                     didRemoveBlock:^(void) {
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             [self.addButton setSelected:NO];
                                                         });
                                                     }];
#endif
        
    }

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)awakeFromNib{
    [super awakeFromNib];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRemoveResource:)
                                                 name:IMF_DID_REMOVE_RESOURCE
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didAddResource:)
                                                 name:IMF_DID_ADD_RESOURCE
                                               object:nil];
    
    //shouldRelayout = YES;
    DLog(@"awakeFromNib")
    BA_LABEL_SET_FONT_LIGHT(self.titleLabel);
    BA_LABEL_SET_FONT_LIGHT(self.authorLabel);
    BA_LABEL_SET_FONT_REGULAR(self.typeLabel);
    BA_LABEL_SET_FONT_LIGHT(self.seriesButton.titleLabel);
    BA_LABEL_SET_FONT_LIGHT(self.addButton.titleLabel);
    BA_LABEL_SET_FONT_LIGHT(self.reserveButton.titleLabel);
    
    [self.arrowImageView setImage:[[BALibrarySettings instance] getCachedNormalCustomerColoredImageNamed:@"searchResultCell_right_arrow"]];
    [self.titleLabel setText:@""];
    
    self.roundDotView.layer.cornerRadius = 4;
    self.roundDotView.hidden=YES;
    
    //hidden for now: BA_LABEL_SET_FONT_MEDIUM(self.shelfMarkNumber);
    
    [self.reserveButton setTitleColor:[UIColor colorWithWhite:0.25 alpha:1] forState:UIControlStateNormal];
    self.reserveButton.layer.borderColor = [UIColor colorWithWhite:0.75 alpha:1].CGColor;
}

/*
- (void)prepareForReuse
{
    //[[LazyLoadManager instance] cancelConnectionsForOwner:self];
    [super prepareForReuse];
}
*/
 
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) didAddResource:(NSNotification *)notification{
    NSString *identifier = [notification object];
    if ([self.record.identifier isEqual:identifier]) {
        [self.addButton setSelected:YES];
    }
    
}

- (void) didRemoveResource:(NSNotification *)notification{
    NSString *identifier = [notification object];
    if ([self.record.identifier isEqual:identifier]) {
        [self.addButton setSelected:NO];
    }
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    if (frame.size.height!=self.contentView.frame.size.height) {
        self.contentView.frame = self.bounds;
    }
}

-(void)setIsShowingMoreView:(BOOL)isShowingMoreView
{
    _isShowingMoreView = isShowingMoreView;
    
    [self.moreView setHidden:!self.isShowingMoreView];
}

-(void)setLibrarianMode:(BOOL)librarianMode{
    _librarianMode = librarianMode;
    if (librarianMode) {
        [self.coverImageView setHidden:YES];
        self.titleLableLeadingSpace.constant = 15;
        //if(library.hasIMF)
        [self.addButton setHidden:NO];
    }
    else{
        [self.coverImageView setHidden:YES];
        self.titleLableLeadingSpace.constant = 72;
    }
}

- (void)setRecord:(BARecord *)record
{
#ifdef BA_IMF_BUILD
    if ([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        self.addButton.hidden = NO;
        if ([[IMFPackageEditManager instance] hasResourceWithIdentifier:record.identifier]) {
            [self.addButton setSelected:YES];
        } else {
            [self.addButton setSelected:NO];
        }
    } else{
        self.addButton.hidden = YES;
    }
#else
    self.addButton.hidden = YES;
#endif
    
    if(record == _record){
        //same record, see if we should update cover
        
        UIImage* coverImage = [[BACoverUrlAndAvailabilityMemoryCache instance] getSearchResultCellSizedCoverImageForIdentifier:record.identifier];
        if (coverImage!=nil) {
            if (self.coverImageView.image != coverImage) {
                DLog(@"old image %x new image %x",(int)self.coverImageView.image,(int)coverImage);
                //a new image has arrived!
                self.coverImageView.image = coverImage;
                self.coverImageView.alpha = 0;
                self.coverImageView.hidden=NO;
                self.iconImageView.hidden=NO;

                [UIView animateWithDuration:0.35
                                      delay:(self.frame.origin.y * 0.0001)
                                    options:0
                                 animations:^{
                                     self.coverImageView.alpha = 1.0;
                                     self.iconImageView.alpha = 0;
                                 }
                                 completion:^(BOOL finished) {
                                     self.iconImageView.hidden=YES;
                                 }];
            }
        }
         
        //NB: IF SAME RECORD, THEN BAIL OUT NOW!
        return;
    }
    
    _record = record;

    
    UIImage* coverImage = [[BACoverUrlAndAvailabilityMemoryCache instance] getSearchResultCellSizedCoverImageForIdentifier:record.identifier];
    if (coverImage!=nil) {
        [self.coverImageView setImage:coverImage];
        self.coverImageView.alpha=1;
        self.coverImageView.hidden=NO;
        self.iconImageView.hidden=YES;
    } else {
        UIImage* iconImage = [[BALibrarySettings instance] getIconForMaterialType:record.type
                                                                contextIdentifier:BATypeIconContextSearchResultsList
                                                                            color:[UIColor colorWithWhite:0.65 alpha:1]];
        [self.iconImageView setImage:iconImage];
        self.iconImageView.alpha=1;
        self.iconImageView.hidden=NO;
        self.coverImageView.hidden=YES;

    }
     
    
    //shouldRelayout = YES;
    
    
    [self.titleLabel setText:record.title];

    [self.typeLabel setText:record.type];
    
    NSString* authors = [BAUtils makeCommaSeparatedStringFromStrings:record.creators];
    
    if ([authors length]>0) {
        authors = [@"AF: " stringByAppendingString:[authors uppercaseString]];
    } else {
        authors = @""; //to avoid the string NULL
    }
    [self.authorLabel setText:authors];
    
    if (record.moreInSameSeries && [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
        [self.seriesButton setHidden:NO];
    }
    else{
        [self.seriesButton setHidden:YES];
    }
    
    self.reserveButton.hidden = YES; //always hide reserve button, until subsequent call setting availability info
    
    //grey dot deprecated: self.roundDotView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.17];
    self.roundDotView.hidden=YES; //always start with hidden


    
    [self layoutIfNeeded];
}

- (IBAction)reserveButtonClicked:(id)sender {
        
        // All instances of TestClass will be notified
    if (self.availability!= nil && self.availability.isReservable && [self.availability.reservationId length]>0) {
        if (self.searchResultDelegate) {
            [self.searchResultDelegate searchResultCell:self clickedReserveButtonWithAvailability:self.availability title:self.record.title];
        } else {
            [BAAddReservationViewController createAddReservationDialogWithReservationId:self.availability.reservationId title:self.record.title];
        }
    }

}

-(void)setAvailability:(BAAvailability *)availability
{
    _availability = availability;
    if (availability) {
        if ([availability.reservationId length]>0 && availability.isReservable) {
            BAPatronSettings* patronsettings = [BAPatronSettings instance];
            if (![patronsettings isUserAllowedIMFEditorAccessForCurrentLibrary] || [patronsettings isUserAllowedLibrarianAccessForCurrentLibrary]) {
                //only show reserve button for ordinary user or librarian (without imf)
                self.reserveButton.hidden=NO;
            }
        }
        if (availability.isReservable && [availability.homeAt count]>0) {
            self.roundDotView.backgroundColor = [UIColor colorWithRed:0 green:195.0/255.0 blue:118.0/255.0 alpha:1]; //green
            self.roundDotView.hidden = NO;
        } else if(availability.isReservable && [availability.homeAt count]==0) {
            self.roundDotView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:8.0/255.0 blue:9.0/255.0 alpha:1]; //red
            self.roundDotView.hidden = NO;
        } else {
            //this means "not to be borrowed"
            //purple dot deprecated: self.roundDotView.backgroundColor = [UIColor colorWithRed:157.0/255.0 green:12.0/255.0 blue:199.0/255.0 alpha:1]; //purple
            self.roundDotView.hidden = YES;
        }
    }
}


-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    self.myBackgroundView.backgroundColor = highlighted ? [UIColor colorWithWhite:221.0/255.0 alpha:1] : [UIColor colorWithWhite:242.0/255.0 alpha:1];
}

@end
